package com.sxds.wn.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Description: <p>通过URL请求映射到实际的JSP文件上控制器</p>
 * Content Desc:<p>通过URL请求映射到实际的JSP文件上控制器<p>
 * Copy Right of Personal Tangtao 2007-2020
 * @author Andy
 * @version 1.0 Create Date:@2008-11-13
 */
public class FileViewController implements Controller {

	//缓存url地址
	private static Map urlCache = new HashMap();
	//前缀
	private String prefix = "";
	//后缀
	private String suffix = "";
	
	/**
	 * 解析URL获取包装实际jsp文件实际路径的ModelAndView
	 * @see org.springframework.web.servlet.mvc.Controller.handleRequest()
	 */
	public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String uri = request.getRequestURI();
		String viewName = (String)urlCache.get(uri);
		if( viewName==null ){
			viewName = this.getViewNameForRequest(request);
			urlCache.put(uri, viewName);
		}
		return new ModelAndView(viewName);
	}
	
	/**
	 * 抽取view name
	 * @param uri
	 * @return java.lang.String
	 */
	private String getViewNameForRequest(HttpServletRequest request){
		String uri = request.getRequestURI();
		int begin = uri.indexOf('/', 1);
		if (request.getContextPath() != null) {
			begin = uri.indexOf('/', request.getContextPath().length());
		}
		if (begin == -1) {
			begin = 0;
		} else {
			begin++;
		}
		int end;
		if (uri.indexOf(";") != -1) {
			end = uri.indexOf(";");
		} else if (uri.indexOf("?") != -1) {
			end = uri.indexOf("?");
		} else {
			end = uri.length();
		}
		String fileName = uri.substring(begin, end);
		if (fileName.indexOf(".") != -1) {
			fileName = fileName.substring(0, fileName.lastIndexOf("."));
		}
		return new StringBuffer(prefix==null ? "":prefix).append(fileName).append(suffix==null?"":suffix).toString();
	}

	/**
	 * @return the prefix
	 */
	public String getPrefix() {
		return prefix;
	}

	/**
	 * @param prefix the prefix to set
	 */
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	/**
	 * @return the suffix
	 */
	public String getSuffix() {
		return suffix;
	}

	/**
	 * @param suffix the suffix to set
	 */
	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

}
